package com.cdu.guoxinan.www.smartcom.controller;

import com.cdu.guoxinan.www.smartcom.aop.Annotation.OperationLog;
import com.cdu.guoxinan.www.smartcom.service.AIService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;

import javax.annotation.Resource;

import java.util.HashMap;

@RestController
@RequestMapping("/ai")
@Api(tags = "智能助手")
public class AIController {
    @Resource
    private AIService aiService;
    @Value("${ai.url}")
    private String url;
    @Value("${ai.model}")
    private String model;
    @Value("${ai.stream}")
    private boolean stream;
    @PostMapping("/query")
    @ApiOperation("请求智能助手")
    @OperationLog(description = "请求智能助手")
    public Flux<String> requestAI(@RequestBody HashMap<String, Object> massage) {
        Object questionObj = massage.get("question");
        Object userIdObj = massage.get("user_id");

        String prompt = (questionObj != null) ? questionObj.toString() : "";

        Long use_id = null;
        if (userIdObj != null) {
            if (userIdObj instanceof Number) {
                use_id = ((Number) userIdObj).longValue();
            } else {
                try {
                    use_id = Long.parseLong(userIdObj.toString());
                } catch (NumberFormatException ignored) {
                    // 可以记录日志或抛出异常
                }
            }
        }

        return aiService.streamQuery(prompt, use_id);
    }
}
